<template>
	<view class="pb-4">
		<view class='text-center pt-8 pb-4'>
			<image class="logo-img" src="/static/login/login-bg.png"></image>
		</view>
		<view class='max-w-80 mx-auto px-5'>
			<view class='mb-4'>
				<LoginInput type="text" @change="inputChange($event,'account')" placeholder="请输入手机号码" prefixIcon="icon-person" ref="account"/>
			</view>
			<view v-if="!isValidCodeMode || isRegisterMode" :class="{'mb-4': isRegisterMode}">
				<LoginInput type="password" @change="inputChange($event,'pwd')" placeholder="请输入密码" prefixIcon="icon-unlock" ref="pwd"/>
			</view>
			<view v-if="isValidCodeMode || isRegisterMode">
				<LoginInput type="text" @change="inputChange($event,'valiCode')" placeholder="请输入短信验证码" prefixIcon="icon-financial_key" 
					ref="valiCode"
					:disabled="loadingValidCode"
					@clickSuffixText="getValidCode"
					:suffixText="waitingValidCode ? `${retrySeconds}秒后重试` : '获取'"/>
			</view>
			<view class="flex pl-3 mt-3 pr-5-3" v-show="!isRegisterMode">
				<link-button extra-class='color-secondary-6-i' @selfClick="toggleLoginWay">{{isValidCodeMode ? "密码登录" : "验证码登录"}}</link-button>
				<view class="flex-1"></view>
				<link-button extra-class='color-secondary-6-i' @selfClick="register(true)">注册</link-button>
			</view>
			<view class='pl-3 mt-1' :class="{hidden: !errMes}">
				<text class='text-l color-error'>{{errMes || "空空空"}}</text>
			</view>
			<self-button extra-class="mt-7-3" @click="loginOrRegister">{{isRegisterMode ? "注册" : "登录"}}</self-button>
			<link-button @selfClick="register(false)" v-show="isRegisterMode" extra-class='mt-3 color-secondary-6-i'>已有账户，直接登录</link-button>
		</view>
	</view>
</template>

<script>
	import { ref,onMounted,getCurrentInstance } from "vue";
	import LinkButton from "@/components/common/LinkButton.vue";
	import LoginInput from "@/components/LoginInput.vue";
	import SelfButton from "@/components/common/SelfButton.vue";
	import { getAllSpecialColumns } from "@/base/api/special-columns.js";
	import { appUserRegister,getVeriCode,doLogin } from "@/base/api/login.js";
	import { verifyCellphone } from "@/utils/verify.js";
	import authCache from "@/utils/cache/authCache.js";
	
	const RETRY_VALID_CODE_SECONDS = 5;
	export default {
		components:{
			LinkButton,
			LoginInput,
			SelfButton
		},
		onReady(){
		},
		onHide(){
			console.log('login hide');
			this.clearWaitingInter();
		},
		onShow(){
			console.log('login show');
		},
		setup(){
			const errMes = ref("");
			//form配置
			const formData = ref({
				account: '',
				pwd: '',
				valiCode: ''
			});
			function inputChange(e,key){
				formData.value[key] = e;
				errMes.value = '';
			}
			//验证码模块
			const isValidCodeMode = ref(false);
			const loadingValidCode = ref(false);
			const waitingValidCode = ref(false);
			const retrySeconds = ref(RETRY_VALID_CODE_SECONDS);
			let waitingValidCodeInter = null;
			async function getValidCode(){
				const mes = verifyCellphone(formData.value.account);
				console.log("getValidCode",mes);
				if(mes){
					errMes.value = mes;
					return;
				}
				if(waitingValidCodeInter) return;
				loadingValidCode.value = true;
				const resp = await getVeriCode({
					phone: formData.value.account
				});
				loadingValidCode.value = false;
				waitingValidCode.value = true;
				waitingValidCodeInter = setInterval(() => {
					if(retrySeconds.value === 1){
						clearWaitingInter();
						return;
					}
					retrySeconds.value--;
				},1000);
			}
			function clearWaitingInter(){
				waitingValidCode.value = false;
				clearInterval(waitingValidCodeInter);
				waitingValidCodeInter = null;
				retrySeconds.value = RETRY_VALID_CODE_SECONDS;
			}
			//登录
			const form = ref();
			async function loginOrRegister(){
				const model = formData.value;
				const mes = verifyCellphone(formData.value.account);
				if(mes){
					errMes.value = mes;
					return;
				}
				if(!model.pwd && (!isValidCodeMode.value || isRegisterMode.value)){
					errMes.value = "请输入密码";
					return;
				}
				if(!model.valiCode && (isValidCodeMode.value || isRegisterMode.value)){
					errMes.value = "请输入验证码";
					return;
				}
				if(isRegisterMode.value){
					const re = await appUserRegister({
						cellphone: model.account,
						password: model.pwd,
						smsCode: model.valiCode
					});
					if(re){
						uni.showToast({
							title: "注册成功，请重新登录"
						});
						isRegisterMode.value = false;
					}
				}else{
					const obj = {
						cellphone: model.account
					};
					if(isValidCodeMode.value){
						obj.smsCode = model.valiCode;
					}else{
						obj.password = model.pwd;
					}
					try{
						const resp = await doLogin(obj);
						//登录成功 存token
						authCache.setToken(resp.token);
						const info = {...model};
						//开发阶段 默认缓存用户信息
						authCache.setRemUserInfo(info);
						delete info.pwd;
						//缓存用户信息
						authCache.setUserInfo(info);
						uni.switchTab({
							url: "/pages/home/info/info"
						})
					}catch(ex){
						errMes.value = ex.msg;
					}
				}
			}
			//
			function toggleLoginWay(){
				errMes.value = '';
				isValidCodeMode.value = !isValidCodeMode.value;
			}
			//注册
			const isRegisterMode = ref(false);
			function register(isRegister){
				errMes.value = '';
				isRegisterMode.value = isRegister;
			}
			//
			onMounted(async () => {
				const userInfo = authCache.getRemUserInfo();
				const { ctx } = getCurrentInstance();
				if(userInfo){
					for(let i in userInfo){
						const ref = ctx.$refs[i];
						if(ref){
							ref.setValue(userInfo[i]);
						}
					}
					Object.assign(formData.value,userInfo);
				}
			});
			return {
				formData,
				loginOrRegister,
				toggleLoginWay,
				register,
				isValidCodeMode,
				loadingValidCode,
				getValidCode,
				waitingValidCode,
				retrySeconds,
				form,
				clearWaitingInter,
				isRegisterMode,
				inputChange,
				errMes
			}
		}
	}
</script>
<style>
	.logo-img{
		width: 452rpx; 
		height: 436rpx;
	}
</style>